package com.cn.book.security;

import com.cn.book.models.JwtUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("userDetailsService")
public class MemberServiceImpl implements UserDetailsService {

    private static final PasswordEncoder BCRYPT = new BCryptPasswordEncoder();

    @Value("${spring.security.user.name}")
    private String hardcodedUser;

    @Value("${spring.security.user.password}")
    private String password;

    @Override
    public JwtUser loadUserByUsername(String username) throws UsernameNotFoundException {
        //对密码加密
        String hardcodePassword = BCRYPT.encode(password);

        if (!username.equals(hardcodedUser)) {
            throw new UsernameNotFoundException("Not user found with " + username);
        }

        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        grantedAuthorityList.add(simpleGrantedAuthority);
        return new JwtUser(hardcodedUser, hardcodePassword, grantedAuthorityList);
    }
}
